package org.ourguy.mymoviesandshows;

import org.ourguy.mymoviesandshows.datamodel.Episode;
import org.ourguy.mymoviesandshows.managers.DataAccessException;
import org.ourguy.mymoviesandshows.managers.DataAccessManager;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class EpisodeActivity extends Activity {

	private DataAccessManager menager;
	private Episode episode;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.episode_layout);
		
		menager = DataAccessManager.getInstance(this);
		
		new LoadEpisode(this, getIntent().getStringExtra("show"), getIntent().getIntExtra("season",1), getIntent().getIntExtra("episode",1)).execute();
		// sliding between tabs
		final GestureDetector mGestureDetector = new GestureDetector(this,
				new GestureDetector.SimpleOnGestureListener() {

					public boolean onFling(MotionEvent e1, MotionEvent e2,
							float velocityX, float velocityY) {
						int dx = (int) (e2.getX() - e1.getX());
						// don't accept the fling if it's too short
						// as it may conflict with a button push
						if (Math.abs(dx) > 100 && Math.abs(velocityX) > 200) {
							if (velocityX > 0 && episode.getNumber() > 1) {
								Intent intent = new Intent(getApplicationContext(), EpisodeActivity.class);
						    	intent.putExtra("show", episode.getSeriesId());
						    	intent.putExtra("season", episode.getSeasonNumber());
						    	intent.putExtra("episode", episode.getNumber() - 1);
								startActivity(intent);
							} else  {//TODO stop sliding on last episode
								Intent intent = new Intent(getApplicationContext(), EpisodeActivity.class);
						    	intent.putExtra("show", episode.getSeriesId());
						    	intent.putExtra("season", episode.getSeasonNumber());
						    	intent.putExtra("episode", episode.getNumber() + 1);
								startActivity(intent);
							}
							return true;
						} else {
							return false;
						}
					}
				});

		View.OnTouchListener gestureListener = new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				return mGestureDetector.onTouchEvent(event);
			}
		};
		
		LinearLayout v= (LinearLayout) findViewById(R.id.linearLayout);
		v.getRootView().setOnTouchListener(gestureListener);
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		return super.onTouchEvent(event);
	}
	
	 @Override
		public boolean onCreateOptionsMenu(Menu menu) {
			  MenuInflater inflater = getMenuInflater();
			  inflater.inflate(R.menu.main_menu, menu);
			  return true;
		}
		 
		@Override
		public boolean onOptionsItemSelected(MenuItem item) {
			// Handle item selection
			switch (item.getItemId()) {
			case R.id.menuTrackingList:
			{
				Intent intent = new Intent().setClass(getApplicationContext(),
						MyMoviesAndShowsActivity.class);
				intent.putExtra("tab", 0);
				this.startActivity(intent);
				return true;
			}
			case R.id.menuSchedule:
			{
				Intent intent = new Intent().setClass(getApplicationContext(),
						MyMoviesAndShowsActivity.class);
				intent.putExtra("tab", 2);
				this.startActivity(intent);
				return true;
			}
			case R.id.menuAbout:
	        {
	        	Intent intent = new Intent().setClass(getApplicationContext(), AboutActivity.class);
	        	this.startActivity(intent);
	        	return true;
	        }
	        case R.id.menuSearch:
	        {
	        	Intent intent = new Intent().setClass(getApplicationContext(), SearchActivity.class);
	        	this.startActivity(intent);
	        	return true;
	        }
			default:
				return super.onOptionsItemSelected(item);
			}
		}
	
		private class LoadEpisode extends AsyncTask<Void, Void, Boolean> {
	    	String id;
	    	int season;
	    	int episodeNum;
	    	private ProgressDialog dialog;
	    	private Context context;
			
	    	public LoadEpisode(Context activity, String id, int seasonNumber, int episodeNumber) {
	    		this.id = id;
	    		season = seasonNumber;
	    		episodeNum = episodeNumber;
	    		context = activity;
	    		dialog = new ProgressDialog(context);
	    	}

			@Override
			protected Boolean doInBackground(Void... arg0) {
		        try {
		        	episode = menager.getEpisode(id, season, episodeNum);
		        } catch (DataAccessException e) {
		        	return false;
		        }
		        return true;
			}
			
			@Override
	    	protected void onPreExecute() {
	    		this.dialog.setMessage("Please wait until the episode is loaded...");
	    		this.dialog.setIndeterminate(true);
	    		this.dialog.show();
	    	}

			
			@Override
			protected void onPostExecute(final Boolean success) {
				if (dialog.isShowing())
					dialog.hide();
				
				if(success) {
					TextView showTitle = (TextView)findViewById(R.id.showTitle);
					showTitle.setText(menager.getTitle(id).getTitle());
					TextView airTime = (TextView)findViewById(R.id.airDate);
					TextView episodeTitle = (TextView)findViewById(R.id.episodeTitle);
					TextView episodeOverview = (TextView)findViewById(R.id.overview);
					ImageView imageView = (ImageView)findViewById(R.id.episodeImage);
					airTime.setText(episode.getFirstAired().toLocaleString());
					episodeTitle.setText(episode.getNumber() + ": " + episode.getTitle());
					episodeOverview.setText(episode.getOverview());
					imageView.setImageBitmap(episode.getImage().loadInImageView(300));
					
				} else {
				}
			}
		}
}
